﻿using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace classTest
{
    /// <summary>
    /// QueryWindow.xaml 的交互逻辑
    /// </summary>
    public partial class QueryWindow : Window
    {
        private List<FeatureLayer> _tables;// 表集合
        private String sqlString; //查询语句的where子句
        private FeatureLayer selectedTable;// 当前所选要素表对象

        private List<Feature> FeatureQuery { set; get; }

        // 在子窗体类的构造函数中初始化相关成员变量
        public QueryWindow(List<Feature> FeatureQuery1)
        {
            InitializeComponent();
            FeatureQuery = FeatureQuery1;
            Tables = new List<FeatureLayer>();//初始化表集合
            sqlString = string.Empty;//初始化字符串
            selectedTable = null;
            listBoxFields.Items.Clear();//清空字段组合框的内容
            listBoxFieldValue.Items.Clear();//清空字段值组合框的内容
            textBoxWhere.Text = string.Empty;//清空文本框
        }

        // 为该子窗体类添加私有数据成员，并添加相应属性
        public List<FeatureLayer> Tables
        {
            get { return _tables; }
            set { _tables = value; }
        }

        public string SqlString
        {
            get { return sqlString; }
            set { sqlString = value; }
        }

        // 为子窗体的加载事件添加处理代码
        private void windowQuery_Loaded(object sender, RoutedEventArgs e)
        {
            //Console.WriteLine("windowQuery_Loaded:" + Tables.Count);
            if (Tables.Count > 0)//表集合不为空
            {
                foreach (FeatureLayer tb in Tables)// 遍历表，将表名加入组合框
                {
                    comboBoxLayers.Items.Add(tb.FeatureTable.TableName);
                }

                comboBoxLayers.SelectedIndex = 0;
                selectedTable = Tables.ElementAt(comboBoxLayers.SelectedIndex);//根据索引取得表对象
                listBoxFields.Items.Clear();//清空字段组合框内容
                foreach (Field fld in selectedTable.FeatureTable.Fields)//遍历表字段集合，将字段名加入组合框
                {
                    listBoxFields.Items.Add(fld.Name);
                }
                SelectLayerLabel.Content = "SELECT * FROM " + selectedTable.FeatureTable.TableName + " WHERE:";
                buttonClear.IsEnabled = false;
                buttonChecking.IsEnabled = false;
            }
        }

        // 处理图层组合框的选择事件
        private void comboBoxLayers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxLayers.SelectedIndex > -1)//选项有效
            {
                selectedTable = Tables.ElementAt(comboBoxLayers.SelectedIndex);//根据索引取得表对象
                if (selectedTable != null)
                {
                    listBoxFields.Items.Clear();//清空字段组合框内容
                    foreach (Field fld in selectedTable.FeatureTable.Fields)//遍历表字段集合，将字段名加入组合框
                    {
                        listBoxFields.Items.Add(fld.Name);
                    }
                }
                SelectLayerLabel.Content = "SELECT * FROM " + selectedTable.FeatureTable.TableName + " WHERE:";
            }
        }

        // 处理字段列表框的选择事件
        private async void listBoxFields_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (selectedTable != null && listBoxFields.SelectedIndex > -1)//选项有效
            {
                Field selectedField = selectedTable.FeatureTable.Fields.ElementAt(listBoxFields.SelectedIndex);//取得索引的字段
                FeatureQueryResult result = await selectedTable.FeatureTable.QueryFeaturesAsync(new QueryParameters());//构建查询参数对象在表对象上进行查询
                if (result == null) return;

                listBoxFieldValue.Items.Clear();//清空字段值列表框内容
                foreach (Feature ft in result)//遍历查询结果
                {
                    string strValue = null;
                    try
                    {
                        strValue = ft.GetAttributeValue(selectedField).ToString();//取得当前字段值
                    }
                    catch
                    {
                        return;
                    }
                    if (!listBoxFieldValue.Items.Contains(strValue))//检查该值是否已存在
                    {
                        listBoxFieldValue.Items.Add(strValue);//加入字段值列表框
                    }
                }
            }
        }

        // 处理字段列表框的鼠标双击事件
        private void listBoxFields_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (listBoxFields.SelectedIndex > -1)//选择项有效
            {
                string strSelField = listBoxFields.SelectedItem.ToString();
                textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", strSelField); //将所选项填入文本框中
            }
        }

        // 处理字段值列表框的鼠标双击事件
        private void listBoxFieldValue_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (listBoxFieldValue.SelectedIndex > -1)//所选项有效
            {
                string strSelValue = listBoxFieldValue.SelectedItem.ToString();
                if (textBoxWhere.Text.EndsWith("and") || textBoxWhere.Text.EndsWith("or"))//如果文本框字符串结尾为and和or则返回
                {
                    return;
                }
                else
                {
                    int idx = textBoxWhere.Text.LastIndexOf("'");//查找最后一个'符号
                    int idx2 = textBoxWhere.Text.LastIndexOf("%");//如果为模糊查询，则插入值在 % 号前面
                    if (idx2 > 0) idx = idx2;
                    if (idx > 0) textBoxWhere.Text = textBoxWhere.Text.Insert(idx, strSelValue);//在文本框字符串中插入字段值
                }

            }
        }

        // 对九个一组按钮的点击事件进行集中处理
        private void OperatorButtonClick(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;//获取button按钮对象
            switch (btn.Name)//根据button对象的名称来判断当前按下的按钮
            {
                case "buttonEqual": //等于
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "= ''");
                    break;
                case "buttonNotEqual": //不等
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "<> ''");
                    break;
                case "buttonLike": //模糊谓词like
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "like '%%'");
                    break;
                case "buttonLessThan": //小于
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "< ''");
                    break;
                case "buttonLessEqual": //小于等于
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "<= ''");
                    break;
                case "buttonAnd": //与谓词and
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "and");
                    break;
                case "buttonGreaterThan": //大于
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "> ''");
                    break;
                case "buttonGreaterEqual": //大于等于
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", ">= ''");
                    break;
                case "buttonOr": //或谓词or
                    textBoxWhere.Text = string.Concat(textBoxWhere.Text, " ", "or");
                    break;
            }
        }

        // 为前面的查询子窗体中的OK按钮和Cancel按钮的点击事件添加处理代码
        private async void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxWhere.Text == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("未指定选择的条件。请输入所需条件！", "Test 6", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                return;
            }
            if (selectedTable != null)//当前选择的表对象存在
            {
                selectedTable.ClearSelection();

                QueryParameters qParams = new QueryParameters();//创建查询参数对象
                FeatureQueryResult result = null;
                qParams.WhereClause = textBoxWhere.Text.Trim();//获取文本框中的字符串作为查询参数对象的where子句
                try
                {
                    result = await selectedTable.FeatureTable.QueryFeaturesAsync(qParams);//在表上进行查询
                    this.DialogResult = true;//设置窗体对话框退出时的结果为true
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("查询条件出现错误！", "Query Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    return;
                }
                if (result != null && result.Count()>0)//查询结果不为空
                {
                    try
                    {
                        selectedTable.SelectFeatures(result);
                    }
                    catch
                    {

                    }
                    QueryResultWindow qsw = new QueryResultWindow();//构造查询结果窗体对象
                    if (FeatureQuery != null && FeatureQuery.Count>0) FeatureQuery.Clear();
                    foreach (Feature f in result) FeatureQuery.Add(f);
                    qsw.FeatureQuerySet = result;//设置查询结果对象引用
                    qsw.Show();
                    qsw.Activate();
                }
                else
                {
                    MessageBox.Show("查询结果为空");
                }
            }
        }


        private async void buttonChecking_Click(object sender, RoutedEventArgs e)
        {
            QueryParameters qParams = new QueryParameters();//创建查询参数对象
            qParams.WhereClause = textBoxWhere.Text.Trim();//获取文本框中的字符串作为查询参数对象的where子句
            try
            {
                FeatureQueryResult result = await selectedTable.FeatureTable.QueryFeaturesAsync(qParams);//在表上进行查询
                System.Windows.Forms.MessageBox.Show("验证成功！");
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("验证失败！");
            }
        }

        private void buttonClear_Click(object sender, RoutedEventArgs e)
        {
            textBoxWhere.Text = string.Empty;//清空文本框
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void TextBoxWhere_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textBoxWhere.Text == string.Empty)
            {
                buttonClear.IsEnabled = false;
                buttonChecking.IsEnabled = false;
            }
            else
            {
                buttonClear.IsEnabled = true;
                buttonChecking.IsEnabled = true;
            }
        }
    }
}
